<template>
  <div>
    <el-dialog :visible.sync="outSpringDialog" width="35%" :title="title">
      <el-tabs tab-position="left" v-model="activeName">
        <el-tab-pane v-if="title=='增加单 单件出库'" label="excel上传" name="first">
          <el-upload
              class="upload-demo"
              drag
              v-loading="loading"
              element-loading-text="正在上传中，请稍后..."
              :show-file-list="false"
              :headers="headers"
              :action="`${$apiHost}/common/fileImgUrl`"
              :on-success="onSuccess"
              :on-error="onError"
              :before-upload="onBefore"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <!-- <div class="el-upload__tip" slot="tip">大小不超过 800KB</div> -->
          </el-upload>
          <div v-if="isDoc(outFileList)">
            <el-link
                style="font-size: 12px;color: #66b1ff"
                :href="'https://'+outFileList">{{ outFileList }}
            </el-link>
            <el-link icon="el-icon-delete" @click="_deleteFile"></el-link>
          </div>
          <div style="display: flex;justify-content: center;margin-top: 20px">
                        <el-button type="warning" @click="outDetailGet('2')" size="small" v-if="inOutType=='2'">出库明细</el-button>
                        <el-button type="warning" @click="outDetailGet('1')" size="small" v-if="inOutType=='1'">入库明细</el-button>
            <el-button @click="outSpringDialog=false" size="small">取 消</el-button>
            <el-button @click="comfirmOut" type="primary" size="small">确 定</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="手动选择单品" name="second">
          <div style="display: flex;"><p>产品：</p>
            <el-button size="small" type="primary"
                       @click="pushProduceList">增加产品
            </el-button>
          </div>
          <div style="display: flex;align-items: center;margin-top: 10px"
               v-for="(item,index) in addForm.addMaterialsList"
               :key="'addMaterialsList'+index">
            <el-select v-model="item.id" remote @change="changeProduceName" filterable :remote-method="changeProduce"
                       placeholder="请选择" style="width: 350px;" size="small">
              <el-option v-for="item in produceList" :key="item.materialId"
                         :value="item.materialId"
                         :label="item.productName">
              </el-option>
            </el-select>
            <el-input-number style="margin-left:10px" v-model="item.count" :min="0"
                             size="small"></el-input-number>
            <el-link style="font-size: 12px;width: 80px"
                     @click="deleteProduce(addForm.addMaterialsList,index)">删除
            </el-link>
          </div>
          <div style="display: flex;justify-content: center;margin-top: 20px">
                        <el-button type="warning" @click="outDetailGet('2')" size="small" v-if="inOutType=='2'">出库明细</el-button>
                        <el-button type="warning" @click="outDetailGet('1')" size="small" v-if="inOutType=='1'">入库明细</el-button>
            <el-button @click="outSpringDialog=false" size="small">取 消</el-button>
            <el-button @click="comfirmHandle" type="primary" size="small">确 定</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog :visible.sync="outDetail" modal-append-to-body :title="title+'产品明细'">
      <el-button style="float: right" size="small" type="primary" @click="downDetail">下载</el-button>
      <el-table :data="outData" height="500px" style="overflow-y: auto">
        <el-table-column type="index" label="序号"/>
<!--        <el-table-column prop="id" label="产品ID"/>-->
        <el-table-column prop="productCode" label="产品编码"/>
        <el-table-column prop="productName" label="产品名称"/>
        <el-table-column prop="norms" label="规格"/>
        <el-table-column prop="unit" label="单位"/>
        <el-table-column prop="colour" label="颜色"/>
        <el-table-column prop="count" label="数量"/>
        <el-table-column prop="createdAt" label="创建时间"/>
      </el-table>

    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from "xlsx-js-style";

export default {
  name: "multiplePutIn",
  data() {
    return {
      host: this.$imgHost,
      loading: false,
      outDetail: false,
      outData: [],
      outAreaId: "",
      inOutType: "",
      outId: "",
      storeName: "",
      activeName: 'second',
      outSpringDialog: false,
      title: "",
      produceList: [],
      outFileList: [],
      addForm: {
        addMaterialsList: [{
          count: "",
          norms: "",
        }],
      },
    }
  },
  computed: {
    headers() {
      const token = this.$quinn.getStorage('token')
      return {
        token,
      }
    },
  },
  methods: {
    outDetailGet(val) {
      const params = {
        id: this.outId,
        pageSize: 1000,
        inOutType: val,
        pageNumber: 1
      }
      this.$api.newAfterSaleNewInOutMaterials(params).then(res => {
        this.outData = res.data
        if (res.data.length!=0) {
          this.outDetail = true
        } else {
          return this.$message.warning('暂无产品详情！')
        }
      })
    },
    handleOpen(row, val) {
      this.inOutType = val
      this.outSpringDialog = true
      this.outFileList = ""
      this.outId = row.id
      this.storeName = row.storeName
      this.outAreaId = row.areaId
      this.addForm = this.$options.data.call(this).addForm
      if (val == '1') this.title = '增加单 客户退款入库'
      if (val == '2') this.title = '增加单 单件出库'
    },
    pushProduceList() {
      this.addForm.addMaterialsList = [...this.addForm.addMaterialsList, {
        norms: "",
        count: 0
      }]
    },
    deleteProduce(list, index) {
      list.splice(index, 1)
    },
    comfirmHandle() {
      const data = {
        id: this.outId,
        inOutType: this.inOutType,
        addMaterialsList: this.addForm.addMaterialsList
      }
      if (data.addMaterialsList.length > 0) {
        for (let i in data.addMaterialsList) {
          if (data.addMaterialsList[i].count == 0 || !data.addMaterialsList[i].id) {
            this.$message({message: "请选择产品及数量！"});
            return
          }
        }
      }
      this.$api.newAfterSaleAfterSaleNewOut(data).then(res => {
        if (res == 1) {
          this.$message.success("操作成功！")
          this.outSpringDialog = false
        }
      })
    },
    changeProduceName() {
    },
    isDoc(filename) {
      return /\.(xlsx|xls|xltx|xltm)$/i.test(filename);
    },
    changeProduce(val) {
      const params = {
        productName: val,
        areaId: this.outAreaId
      }
      this.$api.materialGetMaterialInfoLikeName(params).then(res => {
        this.produceList = res
      })
    },
    onSuccess(res, file) {
      this.setFile = file.raw
      this.loading = false
      if (res.code !== 200) {
        this.$message(res.msg || "上传失败");
      } else {
        this.$message({message: "导入成功！", type: "success"});
        this.outFileList = res.result[0]
      }
    },
    onError() {
      this.$message("导入失败");
    },
    onBefore(file) {
      this.loading = true
    },
    _deleteFile(i) {
      this.outFileList = ''
    },
    comfirmOut() {
      const formData = new FormData();
      formData.append("file", this.setFile);
      formData.append("afterSaleNewId", this.outId);
      formData.append("areaId", this.outAreaId);
      formData.append("excelUrl", this.outFileList);
      this.$api.afterSaleImportExcelOut(formData).then(res => {
        if (res == 1) {
          this.$message.success("上传成功！")
          this.outSpringDialog = false
          this.addStatus('val', 1)
        }
      })
    },
    downDetail() {
      const wb = XLSX.utils.book_new();
      let data = [['产品编码', '产品名称', '规格', '单位', '颜色', '数量']]
      this.outData.map(el => {
        data.push([el.productCode, el.productName, el.norms, el.unit, el.colour, el.count])
      })
      const ws = XLSX.utils.aoa_to_sheet(data)
      ws['!cols'] = [
        {wpx: 100}, // 第一列宽度为100单位
        {wpx: 150},
        {wpx: 100},
      ]
      // ws['A1'].s = {
      //   alignment: {horizontal: 'center'},
      //   font: {blod: true, color: {rgb: '000000'}},
      //   fill: {fgColor: {rgb: 'ff6a00'}},
      // }
      ws['A1'].hpt = 140
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      // ws['!merges'] = [{s: {r: 0, c: 0}, e: {r: 0, c: 3}}]
      const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'})
      // 创建一个 Blob 对象
      const blob = new Blob([s2ab(wbout)], {type: 'application/octet-stream'})
      // 使用 Blob 对象创建一个链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `${this.storeName}.xlsx`
      // 触发下载
      link.click()
      // 清理
      URL.revokeObjectURL(link.href)

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length)
        const view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
        return buf
      }
    }
  }
}
</script>

<style scoped>

</style>